package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-master/cache"
	"novel-master/models"
	"novel-master/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}

	//判断密码是否错误三次
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}

	var user models.User

	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 2, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "密码正确",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var users []models.User
	redis_key := "list_user_" + c.Param("username")
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&users)
		marshal, _ := json.Marshal(&users)
		cache.Rdb.Set(cache.Ctx, redis_key, string(marshal), time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &users)
	}

	var total int64
	models.DB.Model(&models.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": gin.H{
			"list":  users,
			"total": total,
		},
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	redis_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		models.DB.Debug().Find(&user)
		marshal, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, redis_key, string(marshal), time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": user,
	})
}
